package spring.cloud.tasks.api.controller;


import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import spring.cloud.tasks.api.domain.NameSpaceConfiguration;
import spring.cloud.tasks.api.service.ZooKeeperService;
import spring.cloud.tasks.api.utils.Response;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Name space related operations.
 *
 * @author hebelala
 */
@RequestMapping("/console/namespaces")
public class NameSpaceController {
    @Resource
    private ZooKeeperService zooKeeperService;

    //@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
    @GetMapping
    public Response getOnlineNameSpaceList(final HttpServletRequest request)
            throws RuntimeException {
        List<String> namespaceList = new ArrayList<>();
        List<String> temp = zooKeeperService.getOnlineNameSpaceList();
        if (temp != null) {
            namespaceList.addAll(temp);
        }
        return Response.success(namespaceList);
    }

    //@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
    @GetMapping(value = "/{namespace:.+}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Response getNameSpaceConfigurationByNameSpace(final HttpServletRequest request, @PathVariable String namespace)
            throws RuntimeException {
        NameSpaceConfiguration nameSpaceConfiguration = zooKeeperService.getNameSpaceConfigurationByNameSpace(namespace);
        if (nameSpaceConfiguration == null) {
            throw new RuntimeException("该域名（" + namespace + "）不存在");
        }
        return Response.success(nameSpaceConfiguration);
    }

}
